from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from celery_tasks.sms.tasks import send_sms_code

from .serializers import SMSCheckSerializer
from . import constants
import random


# Create your views here.
# url('^sms_codes/(?P<mobile>1[3-9]\d{9})/$', views.SMSCodeView.as_view()),
class SMSCodeView(GenericAPIView):
    """
    短信验证码
    传入参数：
        mobile, username,
    """
    serializer_class = SMSCheckSerializer

    def get(self, request, mobile):
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)

        sms_code = "%06d" % random.randint(0, 999999)
        print('>>%s<<' % sms_code)

        redis_conn = get_redis_connection('verify_code')
        pl = redis_conn.pipeline()
        pl.setex("sms_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex("send_flag_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.execute()

        # 使用异步发送短信
        # expires = constants.SMS_CODE_REDIS_EXPIRES // 60
        # send_sms_code.delay(mobile, sms_code, expires, constants.SMS_CODE_TEMP_ID)

        return Response({"message": "OK"})
